package mall.repository;

import mall.core.jdbc.Repository;
import mall.entity.Menu;
import org.springframework.jdbc.core.BeanPropertyRowMapper;

import java.util.ArrayList;
import java.util.List;

public class MenuRepository extends Repository {

    public List<Menu> selectList() {
        return jdbcTemplate.query("select * from  menu", new  BeanPropertyRowMapper<>(Menu.class));
    }

    public List<Menu> selectList(Menu menu) {
        StringBuilder sb = new StringBuilder("select * from  menu where 1=1 ");
        List<Object> params = new ArrayList<>();

        if (menu.getId() != null) {
            sb.append(" and id = ?");
            params.add(menu.getId());
        }

        if (menu.getIcon() != null) {
            sb.append(" and `icon` like ?");
            params.add("%" + menu.getIcon() + "%");
        }

        return jdbcTemplate.query(sb.toString(), new BeanPropertyRowMapper<>(Menu.class), params.toArray());
    }


    public int insert(Menu menu) {
        String sql = "insert into menu(icon, title, path) values(?, ?, ?)";
        return jdbcTemplate.update(sql, menu.getIcon(), menu.getTitle(), menu.getPath());
    }

    public int update(Menu menu) {
        String sql = "update   menu set icon = ?, title = ?, path = ? where id = ?";
        return jdbcTemplate.update(sql, menu.getIcon(), menu.getTitle(), menu.getPath(), menu.getId());
    }

    public int deleteById(int id) {
        String sql = "delete from   menu where id = ?";
        return jdbcTemplate.update(sql, id);
    }


    public Menu selectById(int id) {
        String sql = "select * from   menu where id = ?";
        List<Menu> list = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(Menu.class), id);
        return list.isEmpty() ? null : list.get(0);
    }
}
